from flask import Flask,render_template,url_for, redirect,request
from flask_sqlalchemy import SQLAlchemy
from wtforms import TextAreaField
from wtforms.widgets import TextArea
from flask_admin.contrib.sqla import ModelView
from flask_admin import Admin,BaseView,expose,AdminIndexView,helpers, expose
from flask_login import UserMixin,current_user
import flask_login as login
from wtforms import form, fields, validators

db = SQLAlchemy()



class User(db.Model,UserMixin):
	__tablename__ = 'user'
	id = db.Column(db.Integer,primary_key=True)
	username=db.Column(db.String(32),unique=True)
	password=db.Column(db.String(32))
			
		
class Comment(db.Model):
	__tablename__ = 'comment'
	id = db.Column(db.Integer,primary_key=True)
	author=db.Column(db.Text)
	content=db.Column(db.String(32))
	def  __init__(self,author,content):
		self.author=author
		self.content=content
	def add(self):
			try:
				db.session.add(self)
				db.session.commit()
				return 0
			except Exception as e:
				db.session.rollback()
				return e
			finally:
				return 0
			
def getAllcontent():
		Content=[]
		Content=Comment.query.filter_by().all()
		return Content
		

class UserL(db.Model,UserMixin):
	__tablename__ = 'userl'
	id = db.Column(db.Integer,primary_key=True)
	userl_name = db.Column(db.String(20),nullable=False)
	userl_password = db.Column(db.String(20),nullable=False)
	classify=db.relationship('Classify',backref='userl',lazy=True,)
	
	def isExisted(username,password):
		temUser = UserL.query.filter_by(userl_name = username,userl_password=password).first()
		print(temUser)
		#print(tempassword)
		if temUser is None:
			print('登录失败')
			return 0
		else:
			print('登录成功')
			return 1
		
	
	# 一对多:
	#neirong = db.relationship('Neirong',secondary=tags)
	#def  __init__(self,name,password):
			#self.userl_name=name
			#self.userl_password=password
	#def add(self):
				#try:
					#db.session.add(self)
					#db.session.commit()
					#return 0
				#except Exception as e:
					#db.session.rollback()
					#return e
				#finally:
					#return 0
	
class Classify(db.Model):
	__tablename__ = 'classify'

	id=db.Column(db.Integer,primary_key=True)
	classify_name = db.Column(db.String(20),nullable=False)
	userl_id=db.Column(db.Integer,db.ForeignKey('userl.id'),nullable=False)
	content = db.relationship('Content',backref='classify',lazy='dynamic', cascade='all, delete-orphan', passive_deletes = True)
	


class Content(db.Model):
	__tablename__ = 'content'

	id=db.Column(db.Integer,primary_key=True)
	content_title = db.Column(db.String(20),nullable=False)
	content_content = db.Column(db.String(100),nullable=False)
	classify_id=db.Column(db.Integer,db.ForeignKey('classify.id',ondelete='CASCADE'))
	userl_id=db.Column(db.Integer,db.ForeignKey('userl.id'),nullable=False)



#获取账户下的分类和内容
def getAllClassifyContent(Userl):
	neirong=[]
	classify=UserL.query.filter(UserL.userl_name==Userl).first().classify
	for content in classify:
		for article in content.content:
			tem1={}
			tem2={}			 
			tem1["classify"]="%s" % content.classify_name
			tem1["classify_id"]="%s" % content.classify_id
			tem1["userl_id"]="%s" % content.userl_id
			tem2["title"]="%s" % article.content_title
			tem2["content"]="%s" % article.content_content
			tem2["content_id"]="%s" % article.content_id
			tem1["article"]="%s" % tem2
			neirong.append(tem1)
	return neirong
	

#############################################################
#添加分类
def addClassify(title):
	classify=Classify()
	classify.classify_name=title
	classify.userl_id=current_user.id
	db.session.add(classify)
	db.session.commit()
#删除分类
def deleteclassfy(ID):
	id=db.session.query(Classify).filter_by(id=ID).first()
	deteledata(ID)
	db.session.delete(id)
	db.session.commit()
	
#修改分类
def changeclassify(id,title):
	id=db.session.query(Classify).filter_by(id=id).first()
	
	id.classify_name=title
	db.session.commit()
#获取分类内容
def getdata(ID):
	id=db.session.query(Content).filter_by(classify_id=ID).all()
	print(ID)
	print(id)
	return id
#删除分类内的所有相关文章
def deteledata(ID):
	id=db.session.query(Content).filter_by(classify_id=ID).all()
	for i in id:
		db.session.delete(i)
		db.session.commit()
#添加文章
def addcontent(title,id,content):
	current_user.id
	contenta=Content()
	contenta.content_title=title
	contenta.content_content=content
	contenta.classify_id=id
	contenta.userl_id=current_user.id
	db.session.add(contenta)
	db.session.commit()
#修改文章内容
def datachange(id):
	data=db.session.query(Content).filter_by(id=id).first()
	classify=db.session.query(Classify).filter_by(userl_id=current_user.id).all()
	return (data,classify)
	
def dataa(title,classify,content):
	data1=db.session.query(Content).filter_by(classify_id=classify).first()
	data1.content_title=title
	data1.content_content=content
	data1.classify_id=classify
	data1.userl_id=current_user.id
	db.session.add(data1)
	db.session.commit()

	
	
	
	
	
##############################################################
	
#获取账户下的分类
def getAllClassify(User):
	neirong=[]
	classify=UserL.query.filter(UserL.userl_name==User).first().classify
	for content in classify:
			tem1={}		 
			tem1["classify"]="%s" % content.classify_name
			tem1["classify_id"]="%s" % content.id
			tem1["userl_id"]="%s" % content.userl_id
			neirong.append(tem1)
	
	return neirong

#获取对应的文章
def getcontent(id):
		#content=[]
		article=Content.query.filter(Content.content_classify==id).all()
		return article
		
#删除文章
def deleteContent(id):

	y=Content.query.filter_by(id=id).first()
	db.session.delete(y)
	db.session.commit()

#删除数据类别
def deleteContents(id):
	y=Classify.query.filter_by(id=id).first().content.all()
	for i in y:
		db.session.delete(i)
		db.session.commit()
	z=Classify.query.filter_by(id=1).first()
	db.session.delete(z)
	db.session.commit()
	
#修改密码
def changeinfo(user):
	y=User.query.filter_by(username=session.get('username')).first()
	y.username=user
	db.session.commit()

#修改分类名
def changefile(id):
	y=Classify.query.filter_by(username=id).first()
	y.classify_name=id
	db.session.commit()
	
#搜索
def searchfile(name,id):
	data=[]
	#y = Content.query.filter(Content.content_title.like("%"+name+"%")).all()
	#y = Content.query.filter(Content.content_title.like("%"+name+"%")).all()
	y=db.session.query(Content).filter(Content.content_title.like("%"+name+"%")).filter(Content.content_classify==id).all()
	for i in y:
		z={}
		z['id']=i.content_id
		z['title']=i.content_title
		z['content']=i.content_content
		z['classify']=i.content_classify
		
		data.append(z)
	print(data)

#新增文章
def addarticle():
	pass
	

		
#将后台模板归类
class UserlModelview(ModelView):
	def is_accessible(self):
		return current_user.is_authenticated
		
	column_labels = {
				'id': u'id',
				'userl_name': u'用户名',
				'userl_password': u'密码'
			}
	column_list = ('id','userl_name', 'userl_password')
	
	def __init__(self, session, **kwargs):
		super(UserlModelview, self).__init__(UserL, session, **kwargs)
	
		
class ClassifyModelview(ModelView):
	def is_accessible(self):
		return current_user.is_authenticated
	
	column_labels = {
					'id': u'ID',
					'classify_name': u'分类',
					'userl_id': u'分类用户'
				}
	column_list = ('id','classify_name','userl_id')
	def __init__(self, session, **kwargs):
			super(ClassifyModelview, self).__init__(Classify, session, **kwargs)
			
class ContentModelview(ModelView):
	
	def is_accessible(self):
		return current_user.is_authenticated
		
	can_create = False
	
	column_labels = {
					'id': u'ID',
					'content_title': u'标题',
					'content_content': u'内容',
					'classify_id': u'用户分类',
					'userl_id': u'用户'
				}
	column_list = ('id','content_title', 'content_content','classify_id','userl_id')
	def __init__(self, session, **kwargs):
			super(ContentModelview, self).__init__(Content, session, **kwargs)	
					
#创建管理员登录表单
class LoginForm(form.Form):
	login = fields.StringField(validators=[validators.required()])
	password = fields.PasswordField(validators=[validators.required()])

	def validate_login(self, field):
		user = self.get_user()

		if user is None:
			raise validators.ValidationError('请输入正确账号或密码')

		# we're comparing the plaintext pw with the the hash from the db
		#if not check_password_hash(user.password, self.password.data):
		# to compare plain text passwords use
		# if user.password != self.password.data:
			#raise validators.ValidationError('Invalid password')

	def get_user(self):
		data=db.session.query(UserL).filter_by(userl_name=self.login.data).first()
		if(self.login.data!='admin'):
			return None
		if(self.password.data!=data.userl_password):
			return None
		else:
			return data

#管理员注册表单
class RegistrationForm(form.Form):
	login = fields.StringField(validators=[validators.required()])
	#email = fields.StringField()
	password = fields.PasswordField(validators=[validators.required()])

	def validate_login(self, field):
		if db.session.query(UserL).filter_by(userl_name=self.login.data).count() > 0:
			raise validators.ValidationError('用户名已存在')
			


		
class MyAdminIndexView(AdminIndexView):
	@expose('/')
	def index(self):
		if not login.current_user.is_authenticated:
			
			return redirect(url_for('.login_view'))
		else:
			if(current_user.userl_name!='admin'):
				
				return redirect(url_for('loginout'))
			else:
				
				return super(MyAdminIndexView, self).index()

	@expose('/login/', methods=('GET', 'POST'))
	def login_view(self):
		#print(current_user.username)
		# handle user login
		form = LoginForm(request.form)
		if helpers.validate_form_on_submit(form):
			user = form.get_user()
			
			login.login_user(user)

		if login.current_user.is_authenticated:
			
			data=UserL.query.filter_by(userl_name=current_user.userl_name).first()
			print(data.userl_password)
			print(form.password.data)
			if(current_user.userl_name!='admin'):
				return redirect(url_for('loginout'))
			else:
				return redirect(url_for('.index'))
		link = '<p>Don\'t have an account? <a href="' + url_for('.register_view') + '">Click here to register.</a></p>'
		self._template_args['form'] = form
		self._template_args['link'] = link
		return super(MyAdminIndexView, self).index()

	@expose('/register/', methods=('GET', 'POST'))
	def register_view(self):
		form = RegistrationForm(request.form)
		if helpers.validate_form_on_submit(form):
			user = User()

			form.populate_obj(user)
			# we hash the users password to avoid saving it as plaintext in the db,
			# remove to use plain text:
			user.password = generate_password_hash(form.password.data)

			db.session.add(user)
			db.session.commit()

			login.login_user(user)
			return redirect(url_for('.index'))
		link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>'
		self._template_args['form'] = form
		self._template_args['link'] = link
		return super(MyAdminIndexView, self).index()

	@expose('/logout/')
	def logout_view(self):
		login.logout_user()
		return redirect(url_for('.index'))

		
		
#富文本编辑器		
class CKTextAreaWidget(TextArea):
	def __call__(self, field, **kwargs):
		if kwargs.get('class'):
			kwargs['class'] += ' ckeditor'
		else:
			kwargs.setdefault('class', 'ckeditor')
		return super(CKTextAreaWidget, self).__call__(field, **kwargs)

class CKTextAreaField(TextAreaField):
	widget = CKTextAreaWidget()

class MessageAdmin(ContentModelview):
	extra_js = ['//cdn.ckeditor.com/4.6.0/standard/ckeditor.js']
	form_overrides = {
		'content_content': CKTextAreaField
	}




